package com.camelot.boot.module.ai.controller.admin.chat;

import com.alibaba.excel.util.IoUtils;
import com.camelot.boot.framework.common.exception.ServerException;
import com.camelot.boot.framework.common.pojo.CommonResult;
import com.camelot.boot.framework.common.pojo.PageResult;
import com.camelot.boot.module.ai.controller.admin.chat.vo.transfer.AiResumeTransferPageReqVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.transfer.AiResumeTransferVO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiResumeTransferDO;
import com.camelot.boot.module.ai.service.chat.AiResumeTransferService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.camelot.boot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.camelot.boot.module.ai.enums.ErrorCodeConstants.RESUME_DOWNLOAD_FAILED;
import static com.camelot.boot.module.ai.enums.ErrorCodeConstants.RESUME_NOT_FOUND;
import static com.camelot.boot.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;


@Tag(name = "管理后台 - 简历转换结果")
@RestController
@RequestMapping("/ai/chat/resume/transfer")
@Slf4j
public class AiResumeTransferController {

    @Resource
    private AiResumeTransferService aiResumeTransferService;


    @GetMapping("/page")
    public CommonResult<PageResult<AiResumeTransferVO>> page(AiResumeTransferPageReqVO pageReqVO){
        pageReqVO.setUserId(getLoginUserId());
        return CommonResult.success(aiResumeTransferService.page(pageReqVO));
    }

    @GetMapping("/download")
    public void download(@RequestParam Long id, HttpServletResponse response){
        AiResumeTransferDO resumeTransferDO = aiResumeTransferService.getById(id);
        if (resumeTransferDO == null){
            throw exception(RESUME_NOT_FOUND);
        }
        try {
            IoUtils.copy(new FileInputStream(resumeTransferDO.getPath()+"/"+resumeTransferDO.getFileName()),response.getOutputStream());
        } catch (IOException e) {
            throw exception(RESUME_DOWNLOAD_FAILED);
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(resumeTransferDO.getFileName(), StandardCharsets.UTF_8));
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
    }
}
